package com.springboot.aop;

import com.springboot.config.DataSourceHelper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.stream.IntStream;

@Aspect
@Component
public class DBAop {

    // @annotation 表示注解用到方法上，@within 则是类上
    @Pointcut(value = "@annotation(com.springboot.aop.DB) || @within(com.springboot.aop.DB)")
    public void pointcut() {}


    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        // 获取方法上的自定义数据源注解
        DB annotation = method.getAnnotation(DB.class);
        if (annotation == null) {
            annotation = method.getDeclaringClass().getAnnotation(DB.class);
        }

        try {
            if (annotation != null) {
                DataSourceHelper.set(annotation.value());
            }
            return pjp.proceed();
        } finally {
            DataSourceHelper.remove();
        }
    }
}
